<template>
  <div class="component-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      class="top-nav-bar" 
      @click-left="$router.back()" 
      @click-right="isManage = !isManage" 
      fixed 
      placeholder
    >
      <template #left>
        <van-icon name="arrow-left" color="#000" class="icon"/>
        <span>购物车</span>
        <van-icon name="shopping-cart-o" color="#000" class="icon"/>
      </template>
      <template #right>
        <span>{{isManage ? '退出' : '管理'}}</span>
      </template>
    </van-nav-bar>
    <!-- 购物车商品列表 -->
    <div class="list-item" v-for="(goodsInfo, index) in goodsInfoArr" :key="index">
      <van-checkbox v-model="goodsInfo.selected" class="checkbox" checked-color="#ee0a24"></van-checkbox>
      <div class="goods" @click="goGoodsDetail(goodsInfo.goodsId)">
        <!-- 商品图片 -->
        <div class="goods-img">
          <img :src="goodsConstants.goodsPictureBaseURL + goodsInfo.goodsPicturePath" alt="">
        </div>
        <!-- 商品名 -->
        <div class="goods-name">
          <span>{{goodsInfo.goodsName}}</span>
        </div>
        <!-- 商品参数 -->
        <div class="goods-param">
          <span v-for="(param, paramGroup) in goodsInfo.selectParams" :key="paramGroup">
            <!-- <span>{{paramGroup}}</span> -->
            <!-- <span>:</span> -->
            <span>{{param}}</span>
          </span>
        </div>
        <!-- 商品运费 -->
        <div class="goods-freight">
          <span>运费: {{goodsInfo.goodsFreight}}</span>
        </div>
        <!-- 商品价格 -->
        <div class="goods-price">
          <span>￥</span>
          <span>{{goodsInfo.goodsPrice.split('.')[0]}}</span>
          <span>.</span>
          <span>{{goodsInfo.goodsPrice.split('.')[1]}}</span>
        </div>
      </div>
      <!-- 购买数量 -->
      <div class="goods-number">
        <div class="stepper">
          <van-stepper 
            v-model="goodsInfo.goodsNumber" 
            theme="round" 
            button-size="22" 
            disable-input 
            @change="goodsNumberChange(goodsInfo.id, goodsInfo.goodsNumber)"
          />
        </div>
      </div>
    </div>
    <!-- 结算 -->
    <div class="submit">
      <van-submit-bar :price="allMoney*100" :button-text="isManage ? '删除' : '结算'" @submit="onSubmit">
        <van-checkbox v-model="allSelect" checked-color="#ee0a24">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { Checkbox, CheckboxGroup } from 'vant'
import { Stepper } from 'vant'
import { SubmitBar } from 'vant'
import { Dialog } from 'vant'

export default {
  name: 'Cart',
  components: {
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Stepper.name]: Stepper,
    [SubmitBar.name]: SubmitBar,
  },
  data() {
    return {
      isManage: false, // 是否处于管理状态
      goodsInfoArr: [], // 商品信息
      isSelectAll: false, // 是否选择了全部
    }
  },
  computed: {
    // 判断是否需要全选
    allSelect: {
      get() {
        if (this.goodsInfoArr.length === 0) {
          return false
        }
        let allSelect = true
        this.isSelectAll = true
        this.goodsInfoArr.forEach(goodsInfo=>{
          if (!goodsInfo.selected) {
            allSelect = false
            this.isSelectAll = false
          }
        })
        return allSelect
      },
      set() {
        if (this.isSelectAll) { // 如果原来为全选
          this.goodsInfoArr.forEach(goodsInfo=>{
            goodsInfo.selected = false
          })
          this.isSelectAll = false
        } else {// 如果原来不为全选
          this.goodsInfoArr.forEach(goodsInfo=>{
            goodsInfo.selected = true 
          })
          this.isSelectAll = true
        }
      }
    },
    // 计算总金额
    allMoney() {
      let sum = 0
      this.goodsInfoArr.forEach(goodsInfo=>{
        if (goodsInfo.selected) {
          sum += Number(goodsInfo.goodsNumber) * Number(goodsInfo.goodsPrice) + Number(goodsInfo.goodsFreight)
        }
      })
      return sum
    }
  },
  methods: {
    // 前往商品详情页面
    goGoodsDetail(goodsId) {
      this.$router.push({
        name: 'goodsDetail',
        query: {
          goodsId
        }
      })
    },
    // 商品数改变
    goodsNumberChange(userCartInfoId, goodsNumber) {
      // console.log(userCartInfoId, goodsNumber)
      this.req.post(
        'user/update/userCartInfo/',
        {
          userCartInfoId,
          goodsNumber
        }
      ).then(res=>{
        let data = res.data
        if ( data.mark === 1 ) {

        } else {
          this.$toast.fail(data.message)
        }
      }, err=>{
        this.$toast.fail(err)
      })
    },
    onSubmit() {
      if (this.isManage) { // 删除购物车商品
        // console.log('管理删除')
        Dialog.confirm({
          message: '确认删除选中的商品？',
        })
          .then(() => {
            // on confirm
            let userCartInfoIdArr = []
            this.goodsInfoArr = this.goodsInfoArr.filter(goodsInfo=>{
              if (goodsInfo.selected) {
                userCartInfoIdArr.push(String(goodsInfo.id))
              }
              return !goodsInfo.selected // 保留没有被选择的元素
            })
            console.log(userCartInfoIdArr)
            this.req.post(
              'user/delete/userCartInfo/',
              {
                userCartInfoIdArr
              }
            )
          })
          .catch(() => {
            // on cancel
          });
      } else { // 结算购物车商品
        // console.log('结算')
        let goodsIdSelectedArr = []
        this.goodsInfoArr.forEach((goodsInfo)=>{
          if (goodsInfo.selected) {
            goodsIdSelectedArr.push(goodsInfo.id)
          }
        })
        // console.log(goodsIdSelectedArr)
        if (goodsIdSelectedArr.length <= 0) {
          this.$toast.fail('您还未选择商品')
          return
        }
        this.$router.push({
          name: 'submitOrder',
          query: {
            goodsIds: goodsIdSelectedArr
          }
        })
      }
    }
  },
  created() {
    this.req.get(
      'user/get/userCartInfo/',
      {
        params: {
          token: localStorage.getItem('token')
        }
      }
    ).then(res=>{
      let data = res.data
      if (data.mark === 1) {
        this.goodsInfoArr = data.data
      } else {
        // this.$toast.fail(data.message)
      }
    }, err=>{
      this.$toast.fail(err)
    })
  }
}
</script>

<style lang="less" scoped>
.component-container {
  padding-bottom: 5rem;
  min-height: 120vh;
}
// 导航栏样式
.top-nav-bar {
  .icon {
    margin-right: 0.5rem;
    font-size: 1.5rem;
  }
  span {
    font-size: 1.25rem;
  }
}
// 商品列表样式
.list-item {
  position: relative;
  height: 7rem;
  margin: 0.5rem;
  padding: 0.5rem;
  border-radius: 1rem;
  background-color: #fff;
  // 复选框样式
  .checkbox {
    position: absolute;
    top: 50%;
    left: 1rem;
    transform: translateY(-50%);
  }
  // 商品样式
  .goods {
    position: absolute;
    top: 1rem;
    left: 3rem;
    width: 80vw;
    margin: 0 0 0 0.5rem;
    // 商品图片
    .goods-img {
      overflow: hidden;
      width: 6rem;
      height: 6rem;
      border-radius: 1rem;
      img {
        width: 100%;
      }
    }
    // 商品名
    .goods-name {
      position: absolute;
      top: 0.2rem;
      left: 6.5rem;
      span {
        display: block;
        width: 53vw;
        font-weight: 600;
        /*1. 先强制一行内显示文本*/
        white-space: nowrap; 
        /*2. 超出的部分隐藏*/
        overflow: hidden;
        /*3. 文字用省略号替代超出的部分*/
        text-overflow: ellipsis;
      }
    }
    // 商品参数
    .goods-param {
      position: absolute;
      left: 6.5rem;
      bottom: 1.7rem;
      padding: 0.1rem 0.2rem;
      border-radius: 0.3rem;
      background-color: #eee;
      text-align: center;
      line-height: 0.7rem;
      span {
        font-size: 0.7rem;
        margin-right: 0.5rem;
      }
      span:last-child {
        margin-right: 0;
      }
    }
    // 商品运费
    .goods-freight {
      position: absolute;
      bottom: 3rem;
      left: 6.5rem;
      padding: 0.1rem 0.2rem;
      border-radius: 0.2rem;
      background-color: #eee;
      line-height: 0.7rem;
      span {
        font-size: 0.7rem;
      }
    }
    // 商品价格
    .goods-price {
      position: absolute;
      left: 6.5rem;
      bottom: 0rem;
      color: #ee0a24;
      span:nth-child(2) {
        font-size: 1.5rem;
      }
    }
  }
  // 商品数量
  .goods-number {
    position: absolute;
    right: 0.5rem;
    bottom: 1rem;
  }
}
</style>